package com.bwie.gateway.filters;

import com.bwie.common.constants.TokenConstants;
import com.bwie.common.utils.JwtUtils;
import com.bwie.common.utils.StringUtils;
import com.bwie.gateway.config.IgnoreWhiteConfig;
import com.bwie.gateway.utils.GatewayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @ClassName AuthFilter
 * @Description 鉴权过滤 验证token gateway 全局过滤器
 * @Author bl
 * @Date 2025/2/26 11:16
 */
@Component
public class AuthFilter implements GlobalFilter, Ordered {

    @Autowired
    private IgnoreWhiteConfig ignoreWhitesConfig;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 核心过滤方法
     * @param exchange ServerWebExchange 请求的上下文对象 包含了请求、响应对象
     * @param chain GatewayFilterChain 网关过滤器链 放行
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 判断当前请求是否需要拦截 自己的配置 决定 提前准备好哪些请求不拦截
        List<String> whites = ignoreWhitesConfig.getWhites();
        // 获取请求路径
        String path = exchange.getRequest().getURI().getPath();
        // 判断是否匹配
        if (StringUtils.matches(path,whites)){
            return chain.filter(exchange);//放行
        }
        // 获取请求头中的token
        String token = exchange.getRequest().getHeaders().getFirst(TokenConstants.TOKEN);
        // 判断token是否存在
        if (StringUtils.isBlank(token)){
            return GatewayUtils.errorResponse(exchange,TokenConstants.TOKEN_IS_NULL, HttpStatus.UNAUTHORIZED);
        }
        // 判断token是否合法
        try {
            JwtUtils.parseToken(token);
        }catch (Exception e){
            return GatewayUtils.errorResponse(exchange,TokenConstants.TOKEN_WRONG,HttpStatus.UNAUTHORIZED);
        }
        // 判断token是否有效(是否存在于redis中 --> key)
        String userKey = JwtUtils.getUserKey(token);
        Boolean hasKey = redisTemplate.hasKey(TokenConstants.LOGIN_TOKEN_KEY + userKey);
        if (Boolean.FALSE.equals(hasKey)){
            return GatewayUtils.errorResponse(exchange,TokenConstants.TOKEN_WRONG,HttpStatus.UNAUTHORIZED);
        }
        // 放行
        return chain.filter(exchange);
    }

    /**
     * 指定过滤器执行顺序
     * @return 数字值越小，优先级越高
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
